package com.carcontrol.rotate;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;


import com.carcontrol.rotate.base.BaseFragment;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

//咖啡机
public class Fragment_Coffee_Machine extends BaseFragment {
    public static String TAG = "3";

    private FrameLayout v;
    private Context context;

    private ImageView iv_clear_device;  //净化器

    GifImageView iv_route;  //gif控件
    GifDrawable gifDrawable;  //gifDrawable

    Object[] gifObj;    //用于界面离开后gif还能动

    private long loopTime = 1000;  //时间显示间隔   默认100毫秒
    private boolean isThread = true;
    Thread thread;

    //gif——gif动图: 控件类型、控件大小位置、gif动图资源id、能否点击；
    Object[] allParam = new Object[]{
//            new Object[]{"iv", new Rect(373*width/width0-width_d, 151*height/height0-height_d, 777*width/width0, 285*height/height0), R.mipmap.border, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//            new Object[]{"iv", new Rect(684*width/width0-width_d, 208*height/height0-height_d, 101*width/width0, 213*height/height0), R.mipmap.clear_device_off, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
            //开
            new Object[]{"iv", new Rect(418*width/width0-width_d, 258*height/height0-height_d, 103*width/width0, 103*height/height0), R.mipmap.coffee1_off, true, "5181", R.mipmap.coffee1_on, "5191"},
            //关
            new Object[]{"iv", new Rect(949*width/width0-width_d, 258*height/height0-height_d, 103*width/width0, 103*height/height0), R.mipmap.coffee2_off, true, "5281", R.mipmap.coffee2_on, "5291"},
            //净化器动画
            new Object[]{"gif", new Rect(647*width/width0-width_d, 199*height/height0-height_d, 174*width/width0, 218*height/height0), R.mipmap.coffee_machine_gif1, false},
//            //净化器动画
//            new Object[]{"gif", new Rect(647*width/width0-width_d, 199*height/height0-height_d, 174*width/width0, 218*height/height0), R.mipmap.clear_device_gif, false},
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = new FrameLayout(getActivity());
//        v = (FrameLayout) inflater.inflate(R.layout.fragment_coffee_machine, null);

        context = v.getContext();
//        activity = getActivity();

        Log.e("fragment_Third===0", v+"==="+width_d+"==="+height_d);


        initView();

//        isThread = true;
//        loopRead();

//        IntentFilter filter = new IntentFilter("carcontrol.broadcast.action");
//        context.registerReceiver(mReceiver, filter);

        return v;
    }

    protected void doAction1(String myDevice, String myStatus){
        Log.e("f3===doAction1", myDevice+"==="+myStatus);

//        if(myDevice.equals("f003")){
//            if(myStatus.equals("0001")){  //TODO
////                iv_clear_device.setVisibility(View.GONE);
////                iv_route.setVisibility(View.VISIBLE);
//                iv_route.setImageResource(R.mipmap.coffee_machine_gif1);
//                gifDrawable.start();
//
//                gifObj[3] = true;
//            }else{
////                iv_clear_device.setVisibility(View.VISIBLE);
////                iv_route.setVisibility(View.GONE);
//                iv_route.setImageResource(R.mipmap.coffee_machine_gif2);
//                gifDrawable.stop();
//
//                gifObj[3] = false;
//            }
//        }
    }

    @Override
    public void onDestroy() {
        Log.e("f3===onDestroy", "===");

        isThread=false;

        if(thread!=null){
            thread.interrupt();
        }

        super.onDestroy();
    }

    private void initView(){
        for (int i=0; i<allParam.length; i++){
            Object[] obj = (Object[])allParam[i];
            Rect rect = (Rect)obj[1];
            String type = (String)obj[0];

            if("tv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                String name = (String)obj[2];
                int textSize = (int)obj[3];
                int textColor = (int)obj[4];
                TextView tv = new TextView(context);
                tv.setText(name);
                tv.setTextSize(textSize);
                tv.setTextColor(textColor);
                v.addView(tv, params);
            }else if("gif".equals(type)){   //GifImageView 加载gif
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                gifObj = obj;
                int imgSrc = (int)obj[2];
                iv_route = new GifImageView(context);
                iv_route.setImageResource(imgSrc);
                iv_route.setScaleType(ImageView.ScaleType.FIT_XY);
                gifDrawable = (GifDrawable) iv_route.getDrawable();

                boolean isOpen = (boolean)obj[3];
                if(isOpen){
//                    iv_clear_device.setVisibility(View.GONE);
//                    iv_route.setVisibility(View.VISIBLE);
                    gifDrawable.start();
                }else{
//                    iv_clear_device.setVisibility(View.VISIBLE);
//                    iv_route.setVisibility(View.GONE);
                    iv_route.setImageResource(R.mipmap.coffee_machine_off);
                    gifDrawable.stop();
                }

                v.addView(iv_route, params);

            }else if("iv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int imgSrc = (int)obj[2];
                ImageView iv = new ImageView(context);
                iv.setImageResource(imgSrc);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                v.addView(iv, params);

//                if(imgSrc==R.mipmap.clear_device_off){
//                    iv_clear_device = iv;
//                }

                boolean isCanClick = (boolean)obj[3];

//                Log.e("fragment_Third===can", imgSrc+"==="+isCanClick);

                if(isCanClick){
                    iv.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            Log.e("onTouch===coffee", event.getAction()+"==="+MainActivity.curPos);

                            if(MainActivity.curPos!=5) return false;

                            m_myHandler.post(new Runnable() {
                                @Override
                                public void run() {



                                    int imgId = (int)obj[2];
                                    int imgId2 = (int)obj[5];
                                    String cmd = (String)obj[4];
                                    String cmd2 = (String)obj[6];

                                    Log.e("onTouch===coffee", cmd+"==="+cmd2+"==="+event.getAction());

                                    if(event.getAction()==1){

                                        iv.setImageResource(imgId);

                                        if(imgId==R.mipmap.coffee1_off){

                                            iv_route.setImageResource(R.mipmap.coffee_machine_off);
                                            gifDrawable.stop();


                                        }else if(imgId==R.mipmap.coffee2_off){

                                            iv_route.setImageResource(R.mipmap.coffee_machine_on);
                                            gifDrawable.stop();

                                        }

//                                      uartJnit.getInstance().sendCmds(toCmd(cmd));
//                                      sendData(cmd);

                                        send(cmd);

//                                      sendData(new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, 0x5D});
                                    }else if(event.getAction()==0){
                                        if(imgId==R.mipmap.coffee1_off){

                                            iv_route.setImageResource(R.mipmap.coffee_machine_gif1);
                                            gifDrawable.start();

//                                          iv_clear_device.setVisibility(View.GONE);
//                                          iv_route.setVisibility(View.VISIBLE);
//                                          gifObj[3] = true;

//                                          Log.e("onTouch===1", "==="+cmd);

//                                          write(bytes); //TODO
//                                          uartJnit.getInstance().sendCmds(toCmd("F311"));

                                        }else if(imgId==R.mipmap.coffee2_off){

                                            iv_route.setImageResource(R.mipmap.coffee_machine_gif2);
                                            gifDrawable.start();

//                                          iv_clear_device.setVisibility(View.VISIBLE);
//                                          iv_route.setVisibility(View.GONE);
//                                          gifObj[3] = false;


//                                          write(bytes); //TODO
//                                          uartJnit.getInstance().sendCmds(toCmd("F310"));
                                        }

                                        send(cmd2);

                                        iv.setImageResource(imgId2);
                                    }

//                                  write(bytes); //TODO


                                }
                            });

                            return true;
                        }
                    });

//                    iv.setOnClickListener(new View.OnClickListener() {
//
//                        @Override
//                        public void onClick(View v) {
////                        ToastUtil.showMessageApp(context, imgSrc+"==="+obj[2]);
//
//                            int imgId = (int)obj[2];
//                            byte[] bytes = (byte[])obj[4];
//
//                            Log.e("fragment_Third===iv", imgId+"==="+bytes.length+"==="+bytes);
//
////                            if(imgId==R.mipmap.open){
////                                iv.setImageResource(R.mipmap.open2);
////                                obj[2] = R.mipmap.open2;
////
////                                gifDrawable.start();
////                            }else if(imgId==R.mipmap.open2){
////                                iv.setImageResource(R.mipmap.open);
////                                obj[2] = R.mipmap.open;
////                            }else if(imgId==R.mipmap.close){
////                                iv.setImageResource(R.mipmap.close2);
////                                obj[2] = R.mipmap.close2;
////
////                                gifDrawable.stop();
////                            }else if(imgId==R.mipmap.close2){
////                                iv.setImageResource(R.mipmap.close);
////                                obj[2] = R.mipmap.close;
////                            }
//
//                            /* 串口发送字节 */
//                            write(bytes); //TODO
//
//
//                        }
//                    });
                }

            }
        }


    }






    public void sendData(byte[] buffer) {
        Log.e("sendData===", "===" + buffer);
        String data = byteArrayToHexString(buffer);
        Log.e("sendData===1", "Activity cmdcan ===send bytes:" + data);
        Intent intent = new Intent();
        intent.setAction("com.unibroad.candata.receive");
        intent.putExtra("cmd", data);
        context.sendBroadcast(intent);
//
//        //数据发送演示
//        strbuffer.append(">>>>发送：").append(data).append("\n");
//        data_tv.setText(strbuffer);
    }

    /**
     * 字符串转Byte数组工具
     * @param hex
     * @return
     */
    private static byte[] hexStringToByte(String hex) {

        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
    /**
     *  Byte数组转字符串工具
     * @param byteArray
     * @return
     */
    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0) {
            return null;
        }
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    private void loopRead(){
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isThread){
                    try {
                        Thread.sleep(loopTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if(MainActivity.curPos==2){
                        m_myHandler.sendEmptyMessage(1);
                    }


                }

            }
        });
        thread.start();
    }

    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    break;

                case 1:
//                    read(cmd_needle); //TODO

                    Log.e("f3===", "===");

                    break;


                default:
                    break;
            }
            return false;
        }
    });

//    BroadcastReceiver mReceiver = new BroadcastReceiver() {
//        private String action = null;
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            action = intent.getAction();
//
//            Log.e("f3=mReceiver", intent+"==="+action);
//
//            if ("carcontrol.broadcast.action".equals(action)) {
//                int count = intent.getIntExtra("count", 0);
//
//                String myDevice = intent.getStringExtra("feedDevice");
//                String myStatus = intent.getStringExtra("feedStatus");
//
//                Log.e("f3=mReceiver_1", myDevice+"==="+myStatus);
//
//                if(myDevice.equals("f001")){
//                    if(myStatus.equals("0001")){  //TODO
//                        iv_clear_device.setVisibility(View.GONE);
//                        iv_route.setVisibility(View.VISIBLE);
//                        gifDrawable.start();
//
//                        gifObj[3] = true;
//                    }else{
//                        iv_clear_device.setVisibility(View.VISIBLE);
//                        iv_route.setVisibility(View.GONE);
//                        gifDrawable.stop();
//                    }
//                }
//
//
//            }
//        }
//    };


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

    }

}

